import { EventEmitter } from '../base/events'

export class Selector {

    public emitselect = false

    constructor(public target: EventEmitter) {}

    setup(el: raphaeljs.Element, unselectWhenDrag:boolean=false) {

        el.mousedown( ()=>this.down() )
        el.touchstart( ()=>this.down() )

        el.mouseup( ()=>this.up() )
        el.touchend( ()=>this.up() )

        if(unselectWhenDrag) {
            el.drag((dx:number, dy:number)=>this.dragging(dx, dy))
        }
    }

    private down() {
        this.emitselect = true
    }
    private up() {
        if(this.emitselect) {
            ; (this.target as any).canvas.setActiveFigure(this.target)
        }
    }

    public dragging(dx:number, dy:number) {
        if(dx>0 || dy>0)
            this.emitselect = false
    }

    public cancelSelect() {
        this.emitselect = false
    }
}